package handle

import (
	"server/game/cache"
	"server/game/itypes"
	"server/share/config"

	"github.com/hwcer/cosgo"
	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/cosgo/times"
	"github.com/hwcer/cosgo/utils"
	"github.com/hwcer/updater"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
	"github.com/hwcer/yyds/players"
	"github.com/hwcer/yyds/players/player"
)

func init() {
	i := &viper{}
	Register(i)
	cosgo.On(cosgo.EventTypLoaded, func() error {
		players.On(config.Data.Events.OrderVerify, i.verify)
		players.On(config.Data.Events.OrderSubmit, i.Submit)
		return nil
	})
}

type viper struct {
}

func (this *viper) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*viper, *context.Context) interface{})
	return f(this, handle)
}

func (this *viper) verify(u *updater.Updater, args ...int32) {
	if len(args) == 0 {
		return
	}
	iid := args[0]
	c := config.Data.Order[iid]
	if c == nil {
		return
	}
	if len(c.Caller) < 2 || c.Caller[0] != config.Data.Caller.Viper {
		return
	}
	viperConfig := config.Data.Viper[c.Caller[1]]
	if viperConfig == nil {
		_ = u.Errorf("viper config error:%d", c.Caller[1])
	}
}

func (this *viper) Submit(u *updater.Updater, args ...int32) {
	if len(args) == 0 {
		return
	}
	iid := args[0]
	c := config.Data.Order[iid]
	if c == nil {
		return
	}
	if len(c.Caller) < 2 || c.Caller[0] != config.Data.Caller.Viper {
		return
	}
	id := c.Caller[1]
	viperConfig := config.Data.Viper[id]
	if viperConfig == nil {
		_ = u.Errorf("viper config error:%d", id)
		return
	}
	roleDoc := cache.GetRole(u)
	roleAll := roleDoc.All()
	data := utils.CloneMap(roleAll.Viper)

	now := times.Daily(0).Now().Unix()
	p := u.Player().(*player.Player)
	expire, err := p.Times.ExpireWithArray(viperConfig.Expire...)
	if err != nil {
		_ = u.Errorf("viper config expire:%d", id)
		return
	}
	//月卡
	if v := data[id]; v > now {
		data[id] = expire + v - now
	} else {
		data[id] = expire
	}
	roleDoc.Set("viper", data)
}

// Reward 领取VIP奖励
// id int viper id
func (this *viper) Reward(c *context.Context) any {
	id := c.GetInt32("id")

	viperConfig := config.Data.Viper[id]
	if viperConfig == nil {
		return errors.Errorf(0, "viper config error:%d", id)
	}
	roleAll := itypes.Role.All(c.Player.Updater)
	if roleAll.Viper[id] < c.Player.Unix() {
		return c.Error("已经过期")
	}

	dailyHandle := itypes.Daily.Handle(c.Player.Updater)
	dailyData := dailyHandle.All()
	d := utils.CloneMap(dailyData.Viper)
	if d[id] > 0 {
		return c.Error("已经领取")
	}
	d[id] = 1
	dailyHandle.Set("viper", d)
	c.Player.AddItems(viperConfig.Items)
	return nil
}
